<template>
  <view class="modal-overlay" @click="$emit('close')">
    <view class="modal-container" @click.stop>
      <view class="modal-header">
        <text class="modal-title">版本对比</text>
        <text class="modal-close" @click="$emit('close')">✕</text>
      </view>

      <view class="modal-body">
        <!-- 版本选择栏 -->
        <view class="version-selector">
          <view class="selector-item">
            <text class="selector-label">版本1:</text>
            <text class="selector-value">{{ version1.name }} - {{ formatTime(version1.timestamp) }}</text>
          </view>
          <view class="selector-divider">VS</view>
          <view class="selector-item">
            <text class="selector-label">版本2:</text>
            <text class="selector-value">{{ version2.name }} - {{ formatTime(version2.timestamp) }}</text>
          </view>
        </view>

        <!-- 对比内容标签 -->
        <view class="compare-tabs">
          <view 
            v-for="tab in tabs" 
            :key="tab.value"
            class="compare-tab"
            :class="{ active: activeTab === tab.value }"
            @click="activeTab = tab.value"
          >
            <text class="tab-label">{{ tab.label }}</text>
            <text class="tab-badge" v-if="tab.changes > 0">{{ tab.changes }}</text>
          </view>
        </view>

        <!-- 参数对比 -->
        <view class="compare-content" v-if="activeTab === 'params'">
          <view class="compare-section">
            <text class="section-title">基本配置差异</text>
            <view class="diff-table">
              <view class="diff-row">
                <text class="diff-label">预报方案</text>
                <text class="diff-value" :class="{ changed: version1.scheme !== version2.scheme }">
                  {{ version1.scheme }}
                </text>
                <text class="diff-value" :class="{ changed: version1.scheme !== version2.scheme }">
                  {{ version2.scheme }}
                </text>
              </view>
              <view class="diff-row" v-if="version1.settings && version2.settings">
                <text class="diff-label">预热期</text>
                <text class="diff-value" :class="{ changed: version1.settings.warmupDays !== version2.settings.warmupDays }">
                  {{ version1.settings.warmupDays }}天
                </text>
                <text class="diff-value" :class="{ changed: version1.settings.warmupDays !== version2.settings.warmupDays }">
                  {{ version2.settings.warmupDays }}天
                </text>
              </view>
              <view class="diff-row" v-if="version1.settings && version2.settings">
                <text class="diff-label">预见期</text>
                <text class="diff-value" :class="{ changed: version1.settings.forecastDays !== version2.settings.forecastDays }">
                  {{ version1.settings.forecastDays }}天
                </text>
                <text class="diff-value" :class="{ changed: version1.settings.forecastDays !== version2.settings.forecastDays }">
                  {{ version2.settings.forecastDays }}天
                </text>
              </view>
            </view>
          </view>

          <view class="compare-section" v-if="paramsDiff.length > 0">
            <text class="section-title">模型参数差异 ({{ paramsDiff.length }}项)</text>
            <view class="diff-table">
              <view v-for="diff in paramsDiff" :key="diff.key" class="diff-row">
                <text class="diff-label">{{ diff.label }}</text>
                <text class="diff-value changed">{{ diff.value1 }}</text>
                <text class="diff-value changed">{{ diff.value2 }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 降雨对比 -->
        <view class="compare-content" v-if="activeTab === 'rainfall'">
          <view class="rainfall-summary">
            <view class="summary-item">
              <text class="summary-label">{{ version1.name }} 总降雨量:</text>
              <text class="summary-value">{{ getTotalRainfall(version1.rainfallData) }} mm</text>
            </view>
            <view class="summary-item">
              <text class="summary-label">{{ version2.name }} 总降雨量:</text>
              <text class="summary-value">{{ getTotalRainfall(version2.rainfallData) }} mm</text>
            </view>
            <view class="summary-item">
              <text class="summary-label">差值:</text>
              <text class="summary-value" :class="{ positive: rainfallDiff > 0, negative: rainfallDiff < 0 }">
                {{ rainfallDiff > 0 ? '+' : '' }}{{ rainfallDiff }} mm
              </text>
            </view>
          </view>

          <!-- 降雨趋势对比图 -->
          <view class="chart-container">
            <canvas 
              canvas-id="rainfallCompareChart" 
              id="rainfallCompareChart"
              class="compare-chart"
              :style="{ width: '100%', height: '350px' }"
            ></canvas>
          </view>
        </view>

        <!-- 结果对比 -->
        <view class="compare-content" v-if="activeTab === 'result'">
          <view class="result-summary">
            <view class="result-card">
              <text class="card-title">{{ version1.name }}</text>
              <view class="card-stats">
                <view class="stat-row">
                  <text class="stat-label">峰值流量:</text>
                  <text class="stat-value">{{ getPeakFlow(version1.result) }} m³/s</text>
                </view>
                <view class="stat-row">
                  <text class="stat-label">峰现时间:</text>
                  <text class="stat-value">{{ getPeakTime(version1.result) }}</text>
                </view>
                <view class="stat-row">
                  <text class="stat-label">平均流量:</text>
                  <text class="stat-value">{{ getAvgFlow(version1.result) }} m³/s</text>
                </view>
              </view>
            </view>
            
            <view class="result-card">
              <text class="card-title">{{ version2.name }}</text>
              <view class="card-stats">
                <view class="stat-row">
                  <text class="stat-label">峰值流量:</text>
                  <text class="stat-value">{{ getPeakFlow(version2.result) }} m³/s</text>
                </view>
                <view class="stat-row">
                  <text class="stat-label">峰现时间:</text>
                  <text class="stat-value">{{ getPeakTime(version2.result) }}</text>
                </view>
                <view class="stat-row">
                  <text class="stat-label">平均流量:</text>
                  <text class="stat-value">{{ getAvgFlow(version2.result) }} m³/s</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 流量过程对比图 -->
          <view class="chart-container">
            <canvas 
              canvas-id="resultCompareChart" 
              id="resultCompareChart"
              class="compare-chart"
              :style="{ width: '100%', height: '400px' }"
            ></canvas>
          </view>
        </view>
      </view>

      <view class="modal-footer">
        <button class="modal-btn" @click="$emit('close')">关闭</button>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'VersionCompare',
  props: {
    version1: {
      type: Object,
      required: true
    },
    version2: {
      type: Object,
      required: true
    }
  },
  emits: ['close'],
  setup(props) {
    const activeTab = ref('result')
    const rainfallChartInstance = ref(null)
    const resultChartInstance = ref(null)

    // 计算参数差异
    const paramsDiff = computed(() => {
      const diffs = []
      
      if (!props.version1.params || !props.version2.params) return diffs

      // 对比initialState
      const state1 = props.version1.params.initialState || {}
      const state2 = props.version2.params.initialState || {}
      Object.keys(state1).forEach(key => {
        if (state1[key] !== state2[key]) {
          diffs.push({
            key,
            label: key,
            value1: state1[key],
            value2: state2[key]
          })
        }
      })

      // 对比parameters
      const params1 = props.version1.params.parameters || {}
      const params2 = props.version2.params.parameters || {}
      Object.keys(params1).forEach(key => {
        if (key === 'monthlyPET') return // 月蒸发量单独处理
        if (params1[key] !== params2[key]) {
          diffs.push({
            key,
            label: key,
            value1: params1[key],
            value2: params2[key]
          })
        }
      })

      return diffs
    })

    // 降雨差异
    const rainfallDiff = computed(() => {
      const total1 = getTotalRainfall(props.version1.rainfallData)
      const total2 = getTotalRainfall(props.version2.rainfallData)
      return (total2 - total1).toFixed(1)
    })

    // 标签页
    const tabs = computed(() => {
      return [
        { value: 'result', label: '结果对比', changes: 0 },
        { value: 'rainfall', label: '降雨对比', changes: Math.abs(rainfallDiff.value) > 0 ? 1 : 0 },
        { value: 'params', label: '参数对比', changes: paramsDiff.value.length }
      ]
    })

    const getTotalRainfall = (rainfallData) => {
      if (!rainfallData || rainfallData.length === 0) return 0
      const total = rainfallData.reduce((sum, item) => sum + (item.value || 0), 0)
      return parseFloat(total.toFixed(1))
    }

    const getPeakFlow = (result) => {
      if (!result?.data?.length) return '-'
      const max = Math.max(...result.data.map(item => item.flow))
      return max.toFixed(2)
    }

    const getPeakTime = (result) => {
      if (!result?.data?.length) return '-'
      const peakItem = result.data.reduce((prev, curr) => 
        curr.flow > prev.flow ? curr : prev
      )
      return formatDateTime(peakItem.time)
    }

    const getAvgFlow = (result) => {
      if (!result?.data?.length) return '-'
      const sum = result.data.reduce((acc, item) => acc + item.flow, 0)
      return (sum / result.data.length).toFixed(2)
    }

    const formatTime = (timestamp) => {
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const formatDateTime = (timeStr) => {
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 初始化降雨对比图表
    const initRainfallChart = () => {
      nextTick(() => {
        const canvas = document.getElementById('rainfallCompareChart')
        if (!canvas) return

        rainfallChartInstance.value = echarts.init(canvas)
        updateRainfallChart()
      })
    }

    const updateRainfallChart = () => {
      if (!rainfallChartInstance.value) return

      const option = {
        title: {
          text: '降雨趋势对比',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: [props.version1.name, props.version2.name],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: (props.version1.rainfallData || []).map((_, i) => i)
        },
        yAxis: {
          type: 'value',
          name: '降雨量(mm)'
        },
        series: [
          {
            name: props.version1.name,
            type: 'bar',
            data: (props.version1.rainfallData || []).map(item => item.value),
            itemStyle: {
              color: '#409eff'
            }
          },
          {
            name: props.version2.name,
            type: 'bar',
            data: (props.version2.rainfallData || []).map(item => item.value),
            itemStyle: {
              color: '#67c23a'
            }
          }
        ],
        dataZoom: [
          {
            type: 'slider',
            start: 0,
            end: 30
          }
        ]
      }

      rainfallChartInstance.value.setOption(option)
    }

    // 初始化结果对比图表
    const initResultChart = () => {
      nextTick(() => {
        const canvas = document.getElementById('resultCompareChart')
        if (!canvas) return

        resultChartInstance.value = echarts.init(canvas)
        updateResultChart()
      })
    }

    const updateResultChart = () => {
      if (!resultChartInstance.value) return

      const option = {
        title: {
          text: '流量过程对比',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: [props.version1.name, props.version2.name],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: (props.version1.result?.data || []).map((item, i) => i),
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '流量(m³/s)'
        },
        series: [
          {
            name: props.version1.name,
            type: 'line',
            data: (props.version1.result?.data || []).map(item => item.flow),
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#409eff'
            },
            itemStyle: {
              color: '#409eff'
            }
          },
          {
            name: props.version2.name,
            type: 'line',
            data: (props.version2.result?.data || []).map(item => item.flow),
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#67c23a'
            },
            itemStyle: {
              color: '#67c23a'
            }
          }
        ],
        dataZoom: [
          {
            type: 'slider',
            start: 0,
            end: 100
          }
        ]
      }

      resultChartInstance.value.setOption(option)
    }

    watch(activeTab, (tab) => {
      if (tab === 'rainfall' && !rainfallChartInstance.value) {
        initRainfallChart()
      } else if (tab === 'result' && !resultChartInstance.value) {
        initResultChart()
      }
    })

    onMounted(() => {
      if (activeTab.value === 'result') {
        initResultChart()
      }
    })

    return {
      activeTab,
      tabs,
      paramsDiff,
      rainfallDiff,
      getTotalRainfall,
      getPeakFlow,
      getPeakTime,
      getAvgFlow,
      formatTime,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  padding: 20px;
}

.modal-container {
  width: 100%;
  max-width: 1200px;
  max-height: 90vh;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.modal-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.modal-close {
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  line-height: 1;
  transition: color 0.3s;
}

.modal-close:hover {
  color: #606266;
}

.modal-body {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.version-selector {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-radius: 8px;
}

.selector-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.selector-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.selector-value {
  font-size: 15px;
  color: #303133;
  font-weight: 600;
}

.selector-divider {
  padding: 8px 16px;
  background-color: #409eff;
  color: #fff;
  font-weight: 600;
  border-radius: 6px;
}

.compare-tabs {
  display: flex;
  gap: 8px;
  border-bottom: 2px solid #e4e7ed;
}

.compare-tab {
  padding: 12px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  margin-bottom: -2px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.compare-tab:hover {
  background-color: #f5f7fa;
}

.compare-tab.active {
  border-bottom-color: #409eff;
}

.tab-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.compare-tab.active .tab-label {
  color: #409eff;
  font-weight: 600;
}

.tab-badge {
  padding: 2px 6px;
  background-color: #f56c6c;
  color: #fff;
  font-size: 11px;
  border-radius: 10px;
  font-weight: 600;
}

.compare-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.compare-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.diff-table {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.diff-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  border-bottom: 1px solid #e4e7ed;
}

.diff-row:last-child {
  border-bottom: none;
}

.diff-label {
  padding: 12px 16px;
  background-color: #f5f7fa;
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  border-right: 1px solid #e4e7ed;
}

.diff-value {
  padding: 12px 16px;
  font-size: 13px;
  color: #606266;
  border-right: 1px solid #e4e7ed;
  font-family: 'Monaco', 'Courier New', monospace;
}

.diff-value:last-child {
  border-right: none;
}

.diff-value.changed {
  background-color: #fff7e6;
  color: #e6a23c;
  font-weight: 600;
}

.rainfall-summary,
.result-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.summary-item {
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.summary-label {
  font-size: 13px;
  color: #909399;
}

.summary-value {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  font-family: 'Monaco', 'Courier New', monospace;
}

.summary-value.positive {
  color: #67c23a;
}

.summary-value.negative {
  color: #f56c6c;
}

.result-card {
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.card-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.card-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
}

.stat-label {
  color: #909399;
}

.stat-value {
  font-weight: 600;
  color: #409eff;
  font-family: 'Monaco', 'Courier New', monospace;
}

.chart-container {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
}

.compare-chart {
  width: 100%;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  background-color: #fafafa;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

.modal-btn {
  padding: 10px 24px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.modal-btn:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}
</style>

